from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from meiduo_mall.apps.oauth import utils
from oauth.models import OpenidUserModel
from users.models import User


class QQAuthUserSerializer(serializers.ModelSerializer):
    access_token = serializers.CharField(label='操作凭证', write_only=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    token = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ['id', 'mobile', 'password', 'access_token', 'sms_code', 'token', 'username']

        extra_kwargs = {
            'username': {
                'read_only': True
            },
            'password': {
                'write_only': True,
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名'
                }
            }
        }

    def validate(self, attrs):
        # 校验access_token 确实是否又被篡改 没篡改就可以取出openid
        access_token = attrs['access_token']
        openid = utils.OAuthQQ.check_save_user_token(access_token)
        if not openid:
            raise serializers.ValidationError('无效的access_token')

        attrs['openid'] = openid  # 保存openid

        # 校验短信验证码
        mobile = attrs['mobile']
        sms_code = attrs['sms_code']

        redis_conn = get_redis_connection('verify_codes')
        real_sms_code = redis_conn.get('sms_%s' % mobile)

        if sms_code != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        # 判断用户是否存在
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            # 如果用户存在 校验密码
            password = attrs['password']
            if not user.check_password(password):
                raise serializers.ValidationError('密码错误')
            attrs['user'] = user

        return attrs

    def create(self, validated_data):
        # 绑定用户
        openid = validated_data['openid']
        user = validated_data.get('user')
        mobile = validated_data['mobile']
        password = validated_data['password']
        # 如果user存在就直接绑定
        if user:
            OpenidUserModel.objects.create(user=user,openid=openid)
        else:
            # 不存在就先创建用户
            User.objects.create_user(username=mobile,mobile=mobile,password=password)

        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user




